package cn.iocoder.yudao.module.reading.controller.app.user;

import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
import cn.iocoder.yudao.module.reading.controller.app.user.vo.UserAccountDeleteReqVO;
import cn.iocoder.yudao.module.reading.controller.app.user.vo.UserProfileRespVO;
import cn.iocoder.yudao.module.reading.controller.app.user.vo.UserSettingsRespVO;
import cn.iocoder.yudao.module.reading.controller.app.user.vo.UserSettingsUpdateReqVO;
import cn.iocoder.yudao.module.reading.controller.app.user.vo.UserSoftDeletedPageReqVO;
import cn.iocoder.yudao.module.reading.controller.app.user.vo.UserSoftDeletedRespVO;
import cn.iocoder.yudao.module.reading.controller.app.user.vo.UserStatsOverviewRespVO;
import cn.iocoder.yudao.module.reading.convert.user.UserSettingsConvert;
import cn.iocoder.yudao.module.reading.dal.dataobject.user.UserSettingsDO;
import cn.iocoder.yudao.module.reading.service.user.UserSettingsService;
import cn.iocoder.yudao.module.reading.service.user.UserService;
import cn.iocoder.yudao.module.reading.service.file.ReadingFileService;
import cn.iocoder.yudao.module.reading.framework.util.StaticResourceUrlUtils;
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
import org.springframework.web.multipart.MultipartFile;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import jakarta.annotation.Resource;
import jakarta.validation.Valid;

import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.error;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.module.reading.enums.ErrorCodeConstants.USER_NOT_EXISTS;

/**
 * 用户 APP - 用户管理
 *
 * @author 芋道源码
 */
@Tag(name = "用户 APP - 用户管理")
@RestController("readingUserController")
@RequestMapping("/reading/user")
@Validated
@Slf4j
public class UserController {

    @Resource
    private UserSettingsService userSettingsService;

    @Resource
    private UserService userService;

    @Resource
    private AdminUserApi adminUserApi;

    @Resource
    private ReadingFileService readingFileService;

    @Resource
    private StaticResourceUrlUtils staticResourceUrlUtils;

    @GetMapping("/profile")
    @Operation(summary = "获得用户信息")
    @PreAuthenticated
    public CommonResult<UserProfileRespVO> getUserProfile() {
        // 获取当前登录用户ID
        Long userId = getLoginUserId();
        
        // 获取用户基本信息
        AdminUserRespDTO user = adminUserApi.getUser(userId);
        if (user == null) {
            throw exception(USER_NOT_EXISTS);
        }

        // 获取用户设置
        UserSettingsDO settings = userSettingsService.getUserSettings(userId);

        // 构建响应
        UserProfileRespVO profile = new UserProfileRespVO();
        profile.setId(user.getId());
        profile.setUsername("user_" + user.getId()); // AdminUserRespDTO 没有 username，使用默认值
        profile.setNickname(user.getNickname());
        profile.setAvatar(user.getAvatar());
        profile.setEmail(""); // AdminUserRespDTO 没有 email，使用空值
        // profile.setPhone(user.getMobile()); // 注释掉手机号设置
        profile.setSettings(UserSettingsConvert.INSTANCE.convert(settings));
        
        return success(profile);
    }

    @GetMapping("/settings")
    @Operation(summary = "获得用户设置")
    @PreAuthenticated
    public CommonResult<UserSettingsRespVO> getUserSettings() {
        Long userId = getLoginUserId();
        UserSettingsDO settings = userSettingsService.getUserSettings(userId);
        return success(UserSettingsConvert.INSTANCE.convert(settings));
    }

    @PutMapping("/settings")
    @Operation(summary = "更新用户设置")
    @PreAuthenticated
    public CommonResult<Boolean> updateUserSettings(@Valid @RequestBody UserSettingsUpdateReqVO updateReqVO) {
        Long userId = getLoginUserId();
        userSettingsService.updateUserSettings(userId, updateReqVO);
        return success(true);
    }

    // =============================================
    // "我的"模块相关接口
    // =============================================

    @PostMapping("/avatar")
    @Operation(summary = "上传用户头像")
    @PreAuthenticated
    public CommonResult<String> uploadAvatar(
            @Parameter(description = "头像文件") @RequestParam("avatar") MultipartFile avatar) {
        Long userId = getLoginUserId();
        log.info("上传用户头像，用户ID: {}, 文件名: {}", userId, avatar.getOriginalFilename());

        try {
            // 使用ReadingFileService上传头像，返回相对路径
            String relativePath = readingFileService.uploadUserAvatar(userId, avatar);
            // 转换为完整URL返回给前端
            String fullUrl = staticResourceUrlUtils.toFullUrl(relativePath);
            log.info("用户头像上传成功，相对路径: {}, 完整URL: {}", relativePath, fullUrl);

            // TODO: 更新用户头像URL到数据库
            // userService.updateUserAvatar(userId, relativePath);

            return success(fullUrl);
        } catch (Exception e) {
            log.error("上传用户头像失败", e);
            return error(500, "上传头像失败: " + e.getMessage());
        }
    }

    @GetMapping("/stats/overview")
    @Operation(summary = "获取用户统计概览")
    @PreAuthenticated
    public CommonResult<UserStatsOverviewRespVO> getUserStatsOverview() {
        Long userId = getLoginUserId();
        log.info("获取用户统计概览，用户ID: {}", userId);

        UserStatsOverviewRespVO result = userService.getUserStatsOverview(userId);
        return success(result);
    }

    @PostMapping("/logout")
    @Operation(summary = "注销账号")
    @PreAuthenticated
    public CommonResult<String> logout() {
        Long userId = getLoginUserId();
        log.info("用户注销，用户ID: {}", userId);

        try {
            // 调用服务层注销账号
            userService.logoutAccount(userId);
            return success("注销成功");
        } catch (Exception e) {
            log.error("用户注销失败，用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            return error(500, "注销失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/account")
    @Operation(summary = "删除用户账号（软删除）")
    @PreAuthenticated
    public CommonResult<Boolean> deleteAccount(@Valid @RequestBody UserAccountDeleteReqVO reqVO) {
        Long userId = getLoginUserId();
        log.info("用户删除账号（软删除），用户ID: {}, 原因: {}", userId, reqVO.getReason());

        try {
            // 调用服务层删除账号（需要密码验证，软删除）
            userService.deleteAccount(userId, reqVO.getPassword(), reqVO.getReason());
            return success(true);
        } catch (Exception e) {
            log.error("用户删除账号失败，用户ID: {}, 错误: {}", userId, e.getMessage(), e);
            return error(500, "删除账号失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/account/permanent/{userId}")
    @Operation(summary = "永久删除用户账号（硬删除）- 管理员操作")
    @PreAuthenticated
    public CommonResult<Boolean> permanentDeleteAccount(
            @PathVariable("userId") Long targetUserId,
            @RequestParam(value = "reason", defaultValue = "管理员操作") String reason) {
        Long currentUserId = getLoginUserId();
        log.info("管理员永久删除用户账号，操作者ID: {}, 目标用户ID: {}, 原因: {}",
                currentUserId, targetUserId, reason);

        try {
            // TODO: 这里应该添加管理员权限验证
            // 调用服务层永久删除账号（硬删除）
            userService.permanentDeleteAccount(targetUserId, reason);
            return success(true);
        } catch (Exception e) {
            log.error("管理员永久删除用户账号失败，操作者ID: {}, 目标用户ID: {}, 错误: {}",
                    currentUserId, targetUserId, e.getMessage(), e);
            return error(500, "永久删除账号失败: " + e.getMessage());
        }
    }

    @GetMapping("/soft-deleted")
    @Operation(summary = "分页查询已软删除用户 - 管理员操作")
    @PreAuthenticated
    public CommonResult<PageResult<UserSoftDeletedRespVO>> getSoftDeletedUserPage(
            @Valid UserSoftDeletedPageReqVO pageReqVO) {
        Long currentUserId = getLoginUserId();
        log.info("管理员查询已软删除用户，操作者ID: {}, 查询条件: {}", currentUserId, pageReqVO);

        try {
            // TODO: 这里应该添加管理员权限验证
            PageResult<UserSoftDeletedRespVO> pageResult = userService.getSoftDeletedUserPage(pageReqVO);
            return success(pageResult);
        } catch (Exception e) {
            log.error("查询已软删除用户失败，操作者ID: {}, 错误: {}", currentUserId, e.getMessage(), e);
            return error(500, "查询已软删除用户失败: " + e.getMessage());
        }
    }

    @PostMapping("/restore/{userId}")
    @Operation(summary = "恢复软删除用户 - 管理员操作")
    @PreAuthenticated
    public CommonResult<Boolean> restoreSoftDeletedUser(
            @PathVariable("userId") Long targetUserId,
            @RequestParam(value = "reason", defaultValue = "管理员恢复") String reason) {
        Long currentUserId = getLoginUserId();
        log.info("管理员恢复软删除用户，操作者ID: {}, 目标用户ID: {}, 原因: {}",
                currentUserId, targetUserId, reason);

        try {
            // TODO: 这里应该添加管理员权限验证
            userService.restoreSoftDeletedUser(targetUserId, reason);
            return success(true);
        } catch (Exception e) {
            log.error("恢复软删除用户失败，操作者ID: {}, 目标用户ID: {}, 错误: {}",
                    currentUserId, targetUserId, e.getMessage(), e);
            return error(500, "恢复用户失败: " + e.getMessage());
        }
    }

}
